package com.example.stag;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.sql.ResultSet;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    public void init() {
        UserSQLOperation.connect();
        CommoditySQLOperation.connect();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        UserSQLOperation.connect();
        CommoditySQLOperation.connect();
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = null;
        try {
            writer = resp.getWriter();
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            String usertype = req.getParameter("usertype");
            ResultSet resultSet =UserSQLOperation.searchByUsername(username);
            // 如果一开始就不存在结果集，则代表用户不存在
            if (!resultSet.next()){
                writer.println("user not exist");
            } else {
                do {
                    // 循环判断，如果有匹配的则返回ok
                    if (resultSet.getString("password").equals(password) &&
                            resultSet.getString("usertype").equals(usertype)) {
                        writer.println("OK");
                        return;
                    }
                } while (resultSet.next());
                writer.println("wrong");
            }
        } catch (Exception e) {
            e.printStackTrace(writer);
            e.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
